//
//  songListController.m
//  Gegeda_music_MY
//
//  Created by lanou3g on 15/11/11.
//  Copyright © 2015年 周莹. All rights reserved.
//

#import "songListController.h"
#import "songListTableViewCell.h"
#import "songListModel.h"
#import "UIImageView+WebCache.h"
#import "MBProgressHUD+MJ.h"
#import "MJRefresh.h"
#import "RadioDetailViewController.h"
#define Url @"http://mobile.ximalaya.com/mobile/discovery/v1/category/album?calcDimension=hot&categoryId=2&device=android&pageId=1&pageSize=20&status=0&tagName=%E7%B2%BE%E9%80%89%7C%E6%AD%8C%E5%8D%95"

#define url1 @"http://mobile.ximalaya.com/mobile/discovery/v1/category/album?calcDimension=hot&categoryId=2&device=android&pageId="
#define url2 @"&pageSize=20&status=0&tagName=%E7%B2%BE%E9%80%89%7C%E6%AD%8C%E5%8D%95"

@interface songListController ()<UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) IBOutlet UITableView *songListTableView;

//数据解析
@property(nonatomic, strong)NSMutableArray *dataArray;

@end

@implementation songListController

#pragma mark - 懒加载
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)songListTableView{
    if (!_songListTableView) {
        _songListTableView = [[UITableView alloc] init];
    }
    return _songListTableView;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [[UIColor alloc] initWithRed:255.0/255 green:222.0/255 blue:249.0/255 alpha:1.0];
    self.songListTableView.delegate = self;
    self.songListTableView.dataSource = self;
    
    [self downLoadGiftDataFinish:^{
        [self.songListTableView reloadData];
    } withIndex:self.index];
    
    //注册cell
    [self.songListTableView registerNib:[UINib nibWithNibName:@"songListTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    //菊花
    [MBProgressHUD showMessage:@"正在加载,请稍等" toView:self.view];
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    
    [self.songListTableView addHeaderWithTarget:self action:@selector(headerHeightDidClicked)];
    [self.songListTableView headerBeginRefreshing];
    [self.songListTableView addFooterWithTarget:self action:@selector(footerefreshing)];
    
    self.songListTableView.headerPullToRefreshText = @"下拉可以刷新";
    self.songListTableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.songListTableView.headerRefreshingText = @"正在帮你刷新中,不客气";
    
    self.songListTableView.footerPullToRefreshText = @"- The End -";
    self.songListTableView.footerReleaseToRefreshText = @"已经到头了";
    self.songListTableView.footerRefreshingText = @"- The End -";
    
    
}

-(void)headerHeightDidClicked
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        if (self.dataArray == nil) {
            
            // 刷新表格
            [self.songListTableView reloadData];
            
        }
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.songListTableView headerEndRefreshing];
    });}

-(void)footerefreshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self downLoadGiftDataFinish:^{
            [self.songListTableView reloadData];
           self.index = (self.songListTableView.contentOffset.y - 1515) / 2000 ;
            
            self.index = self.index + 1;
            NSLog(@"%ld", self.index);
        } withIndex:self.index];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.songListTableView footerEndRefreshing];
        
        
    });
    
}


#pragma mark - 代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //return 10;
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    songListModel *model = self.dataArray[indexPath.row];
    static NSString *cell_id = @"cell";
    songListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id forIndexPath:indexPath];
    [cell setCellDataWithModel:model];
    UIColor *color  = [[UIColor alloc] initWithRed:255.0/255 green:222.0/255 blue:249.0/255 alpha:1.0];
    cell.backgroundColor = color;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

//cell点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    songListModel *model = self.dataArray[indexPath.row];
    RadioDetailViewController *radio = [[RadioDetailViewController alloc] init];
    [self.navigationController pushViewController:radio animated:YES];
    
    radio.albumId = model.albumId;
    radio.position = [NSString stringWithFormat:@"%ld",indexPath.row];
    
}


#pragma mark - 数据请求
-(void)downLoadGiftDataFinish:(void(^)())result withIndex:(NSInteger)index{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *url3 = [NSString stringWithFormat:@"%@%ld%@", url1, index + 1, url2];
        NSURL *url4 = [NSURL URLWithString:url3];
        NSURLRequest *request = [NSURLRequest requestWithURL:url4];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSArray *array =resultDict[@"list"];
            //NSLog(@"%@",array);
            for (NSDictionary *dict in array) {
                songListModel *model = [[songListModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                [self.dataArray addObject:model];
                // NSLog(@"%@", self.dataArray);
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                result();
            });
            
        }];
        
    });
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end